package timer;

import insert.Inserter;
import insert.PositionInserter;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.LinkedList;

import graphic.GamePanel;


public class GameTimerTask implements Runnable{
	GamePanel panel;
	LinkedList<Inserter> inserterList = new LinkedList<Inserter>();
	
	public GameTimerTask(GamePanel panel){
		this.panel = panel;
		addListener();
	}
	
	private void addListener() {
		this.panel.addMouseListener(new MouseAdapter(){
			public void mousePressed(MouseEvent e){
				int x = e.getX();
				int y = e.getY();
				addInserter(new PositionInserter(x,y,10));
			}
		});
	}
	
	public void addInserter(Inserter inserter){
		if(!inserter.isPeriod()){
			inserter.insert(panel);
		}else{
			inserterList.add(inserter);
		}
	}
	
	public void removeInserter(Inserter inserter){
		if(inserterList.contains(inserter)){
			inserterList.remove(inserter);
		}
	}
	
	public void insert(int age){
		for(Inserter inserter:inserterList){
			if(inserter.isPeriod()){
				if(age%inserter.getPeriod()==0){
					inserter.insert(panel);
				}
			}
		}
	}
	
	@Override
	public void run() {
		int age = 0;
		while(true){
			try {
				insert(age);
				Thread.sleep(40);
				panel.agePlus();
				panel.moveParticles(0.05);
				panel.removeParticles();
				panel.repaint();
				age++;
		    }catch(Exception e){
		    	
		    }
		}
	}

}
